<template>
  <div>
    <div
      style="height: 400px; margin-top: 20px"
      ref="liveChart"
    ></div>
  </div>
</template>

<script>
  import * as echarts from "echarts/core";
  import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
  } from "echarts/components";
  import { BarChart } from "echarts/charts";
  import { CanvasRenderer } from "echarts/renderers";
  import dayjs from "dayjs";
  import { unwarp } from "@/utils";
  import { onMounted, onUnmounted } from "vue";

  /**
   * @description: 生成20条数据
   * @param {*}
   * @return {*}
   */
  const dataList = () => {
    let date = [];
    let num = [];
    let nowTime = new Date().getTime();
    for (let i = 0; i < 30; i++) {
      date.push(dayjs(nowTime - i * 1000).format("HH:mm:ss"));
      num.push((Math.random() * 10).toFixed(0) * 1);
    }
    return {
      date: date.reverse(),
      num,
    };
  };

  echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    BarChart,
    CanvasRenderer,
  ]);

  export default {
    name: "LiveChart",
    data() {
      return {
        myChart: null,
        timer: null,
        dataList: dataList(),
      };
    },
    mounted() {
      this.myChart = echarts.init(this.$refs.liveChart);
      this.getNewData();
    },
    methods: {
      getNewData() {
        const option = {
          title: {
            text: "用户访问量",
          },
          grid: {
            left: "0",
            right: "0",
            top: "10%",
            bottom: "0",
            containLabel: true,
          },
          tooltip: {
            trigger: "axis",
          },
          xAxis: {
            data: this.dataList.date,
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              data: this.dataList.num,
              type: "bar",
              showBackground: true,
              backgroundStyle: {
                color: "rgba(180, 180, 180, 0.2)",
              },
            },
          ],
        };

        this.myChart.setOption(option);

        this.timer = setInterval(() => {
          this.dataList.date.shift();
          this.dataList.num.shift();
          this.dataList.date.push(dayjs(new Date().getTime()).format("HH:mm:ss"));
          this.dataList.num.push((Math.random() * 10).toFixed(0) * 1);
          this.myChart.setOption(option);
        }, 1000);
      },
    },
    beforeDestroy() {
      if (this.myChart) {
        this.myChart.dispose();
      }
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
  };
</script>

<style scoped>
  /* Your CSS styles here */
</style>
